import org.dom4j.DocumentHelper
import org.dom4j.Element
import org.dom4j.io.OutputFormat
import org.dom4j.io.XMLWriter
import java.io.StringReader
import java.io.StringWriter


fun main(args: Array<String>) {
    print(pug2xml(Pug(System.getProperty("user.dir") + "/pom.xml").toString()))
}


fun pug2xml(pug: String): String {
    val document = DocumentHelper.createDocument()
    val root = document.addElement("project", "http://maven.apache.org/POM/4.0.0").apply {
        addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        addAttribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
    }

    var list: MutableList<Element> = ArrayList()
    list.add(root)

    // 有bug，属性中包含括号时出现
    val re = "^(\t*)([\\w.-]+)(?:\\((.+?)\\))?(?: (.*))?$".toRegex()
    val attrReg = "([\\w.-]+)=\"([^\"]*)\"(?:\\s|$)".toRegex()

    StringReader(pug).forEachLine {
        if (it.trim().isEmpty()) return@forEachLine

        val matchResult = re.matchEntire(it) ?: throw Exception("parse error on : $it")
        val group = matchResult.groupValues

        val i = group[1].length
        if (i >= list.size) throw Exception("parse error : bad indent")

        if (i < list.size - 1) list = list.subList(0, i + 1)

        val e = list[i].addElement(group[2])

        val attrs = group[3]
        if (attrs != "") {
            if (attrs.replace(attrReg, "").trim() != "")
                throw Exception("parse error on : $attrs")

            val qq = attrReg.findAll(attrs)
            qq.forEach {
                val values = it.groupValues
                e.addAttribute(values[1], values[2])
            }
        }
        e.addText(group[4])
        list.add(e)
    }


    val sw = StringWriter()
    XMLWriter(sw, OutputFormat.createPrettyPrint()).apply {
        write(document)
        flush()
        close()
    }

    return sw.toString()
}


